<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Silex\Application;

use models\User;
use utils\out;

//Request::setTrustedProxies(array('127.0.0.1'));


/** 微信 **/
require_once __DIR__.'/weixin.php';

/** 菜场 **/
require_once __DIR__.'/market.php';

/** 菜 **/
require_once __DIR__.'/commodity.php';

/** 菜单 **/
require_once __DIR__.'/menu.php';

/** 菜篮 **/
require_once __DIR__.'/basket.php';

/** 点赞 **/
require_once __DIR__.'/praise.php';

/** 后台 **/
require_once __DIR__.'/bd.php';

/** 后台菜单 **/
require_once __DIR__.'/bdmenu.php';

/** 后台评论列表 **/
require_once __DIR__.'/bdcomment.php';

/** 评论 ***/
require_once __DIR__.'/comment.php';

/** 首页 **/
$app->get('/', function (Application $app) {
    return $app['twig']->render('index.html', array("marketId" => null));
});

/**数据统计**/
$app->get('/statistics', function (Application $app) {
    return $app['twig']->render('statistics.html');
});

/** 后台登录 **/
$app->get('/login', function (Application $app) {
    return $app['twig']->render('login.html');
});

$app->get('/newlogin', function (Application $app) {
	$openid = time();
	$name = rand(1000, 9999).'普陀';
	$avatar = '';
    $uid = User::add($app['db'], time(), $name, $avatar);
    return $app->json(array("state"=>true, "result"=> array(
            "id" => $uid,
            "openid" => $openid,
            "name" => $name,
            "avatar" => $avatar
            )));
});

/** 用户登录 **/
$app->post('/login', function (Application $app, Request $request) {
    $openid = $request->get('openid');
    $name = $request->get('name');
    $avatar = $request->get('avatar');

    $user = User::getByOpenid($app['db'], $openid);
    if($user) {
        return $app->json(array("success"=>true, "result"=> $user));
    } else {
        $uid = User::add($app['db'], $openid, $name, $avatar);
        return $app->json(array("success"=>true, "result"=> array(
                "id" => $uid,
                "openid" => $openid,
                "name" => $name,
                "avatar" => $avatar
                )));
    }
});

/** error handler **/
$app->error(function (\Exception $e, Request $request, $code) use ($app) {
    if ($app['debug']) {
        return;
    }

    // 404.html, or 40x.html, or 4xx.html, or error.html
    $templates = array(
        'tpls/'.$code.'.html',
        'tpls/'.substr($code, 0, 2).'x.html',
        'tpls/'.substr($code, 0, 1).'xx.html',
        'tpls/default.html',
    );

    return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code);
});
